import json
from crawler.extractors import BaseExtractor, JsonpExtractor
from crawler.fields import ContainerField, TextField, AttrField, JsonField

__all__ = ['YooxMainExtractor', 'YooxDetailExtractor']


class YooxMainInfoExtractor(BaseExtractor):
    container = ContainerField(xpath_selector='//div[@id="itemsGrid"]//div[@class="col-8-24"]')
    spu_id = AttrField(xpath_selector='./div', attr='id')
    brand = TextField(xpath_selector='.//a/div[1]')
    product_name = TextField(xpath_selector='.//a/div[@class="microcategory font-sans"]')
    cost_price = TextField(
        xpath_selector='.//a/div[@class="price"]/div[@class="retail-newprice font-bold"]|.//a/div[@class="price"]/span[@class="fullprice font-bold"]')
    wages = TextField(
        xpath_selector='.//a/div[@class="price"]/div[@class="oldprice-wrapper"]/'
                       'span[@class="oldprice text-linethrough text-light"]')

    url = AttrField(xpath_selector='.//a', attr='href')
    size = TextField(xpath_selector='.//a/div[@class="colorSize"]//span', many=True)


class YooxDetailInfoExtractor(JsonpExtractor):
    color = JsonField(json_selector='$.props.pageProps.initialState.itemApi.colors[*]', many=True)
    gender = JsonField(json_selector='$.props.pageProps.initialState.itemApi.gender')
    size_id_list = JsonField(json_selector='$.props.pageProps.initialState.itemApi.sizes[*]', many=True)
    composition = JsonField(json_selector='$.props.pageProps.initialState.itemApi.descriptions.Composition')
    product_des = JsonField(json_selector='$.props.pageProps.initialState.itemApi.descriptions.ItemDescription')
    atlas_list = JsonField(json_selector='$.props.pageProps.initialState.itemApi.colors[*].imageFormats', many=True)
    colorCode = JsonField(json_selector='$.props.pageProps.initialState.itemApi.colors[*].colorCode', many=True)
    code = JsonField(json_selector='$.props.pageProps.initialState.itemApi.code', many=True)


class YooxMainExtractor:
    @classmethod
    def get_item(cls, response):
        return cls._extract(response)

    @classmethod
    def _extract(cls, response):
        task = response.meta['task']
        sex = task['sex']
        info_list = list()
        for item in YooxMainInfoExtractor.get_items(response):
            info_dict = dict()
            info_dict['title'] = item.product_name
            info_dict['spu_id'] = item.spu_id.split('item_')[1]
            info_dict['brand'] = item.brand
            info_dict['category'] = ''
            info_dict['sex'] = sex
            # 成本价 原价对应公价

            info_dict['cost_price'] = item.cost_price.split('(HKD')[0].replace('US$', '').split(',')[0].replace(".",
                                                                                                                "").strip()

            # 公价
            info_dict['retail_price'] = item.wages.split('(HKD')[0].replace('US$',
                                                                            '').split(',')[0].strip().replace(".",
                                                                                                              "") if item.wages else \
                info_dict[
                    'cost_price']
            info_dict['currency'] = 'USD'
            info_dict['url'] = 'https://www.yoox.com' + item.url if item.url else ''
            # '规格(商品尺寸或者服装尺码表)。此网站暂未发现
            # info_dict['specifications'] = ''

            info_list.append(info_dict)

        return info_list


class YooxDetailExtractor:
    @classmethod
    def get_item(cls, response, resp, num):
        return cls._extract(response, resp, num)

    @classmethod
    def _extract(cls, response, resp, num):
        item = YooxDetailInfoExtractor.get_item(response, resp)
        color_list = item.color
        info_dict = dict()
        for index, color in enumerate(color_list):
            if color['code10'] == item.code[0]:
                info_dict['stock_id_list'] = color['availableSizesIds']
                info_dict['color'] = color['name']
                info_dict['atlas'] = [
                    'https://www.yoox.com/images/items/' + num + '/' + item.code[0] + '_' + _ + '.jpg' for _ in
                    color['imageFormats'] if _.split('_')[0] == color['imageFormats'][0].split('_')[0]]
                break
        size_id_list = item.size_id_list
        end_list = list()
        for stock_info in info_dict['stock_id_list']:
            for size_id in size_id_list:
                if stock_info['id'] == size_id['id']:
                    end_dict = dict()
                    end_dict['size'] = size_id['default']['text']
                    end_dict['stock'] = stock_info['quantity']
                    end_list.append(end_dict)

        # # 性别
        product_des = item.product_des
        del info_dict['stock_id_list']
        # 尺码对应id
        composition = item.composition
        return composition, end_list, product_des, info_dict
